package main

import (
	"context"
	"fmt"
)

type RegisterSvManager struct {
	RegisterMap  map[string]RegisterSv
	RegisterSv   chan string
	UnRegisterSv chan string
}

type RegisterSv struct {
	Sv      map[string]SvStatus
	Clients map[string]Client
}

type SvStatus struct {
	Ctx    context.Context
	Cancel func()
	Status bool
}

//初始化用于注册启动不同品牌型号的服务，统一进行管理
var Register RegisterSvManager
var SvRegister = []string{
	NVFBrand,
}

func initRegister() {
	Register = RegisterSvManager{
		RegisterMap: make(map[string]RegisterSv),
	}
	Register.RegisterEx(SvRegister)
}

func (m *RegisterSvManager) Register(brand string) {
	if _, ok := m.RegisterMap[brand]; !ok {
		m.RegisterMap[brand] = RegisterSv{
			Sv:      make(map[string]SvStatus),
			Clients: make(map[string]Client),
		}
		for k, v := range NewVersionFaceSvMap {
			ctx, cancel := context.WithCancel(context.Background())
			m.RegisterMap[brand].Sv[k] = SvStatus{
				Ctx:    ctx,
				Cancel: cancel,
				Status: true,
			}
			go v()
		}
	} else {
		for k, v := range NewVersionFaceSvMap {
			ctx, cancel := context.WithCancel(context.Background())
			if !m.RegisterMap[brand].Sv[k].Status {
				m.RegisterMap[brand].Sv[k] = SvStatus{
					Ctx:    ctx,
					Cancel: cancel,
					Status: true,
				}
				go v()
			}
		}
	}
}

func (m *RegisterSvManager) RegisterEx(brands []string) {
	for _, v := range brands {
		m.Register(v)
	}
}

func (m *RegisterSvManager) UnRegister(brand string) {
	for _, v := range m.RegisterMap[brand].Sv {
		v.Cancel()
	}
}

func (m *RegisterSvManager) GetClientFromID(id, brand string) Client {
	fmt.Println("register map:", m.RegisterMap)
	fmt.Println("id:", id, "brand:", brand)
	for _, v := range m.RegisterMap[brand].Clients {
		if id == v.GetID() {
			fmt.Println("id:", v.GetID())
			return v
		}
	}
	return nil
}
